<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px"
      label-position="left">
      <el-form-item :label="$t('Department')" prop="deptId">
        <department-select v-model="queryParams.deptId" style="width: 200px" />
      </el-form-item>
      <el-form-item :label="$t('user.Username')" prop="userName">
        <el-input v-model="queryParams.userName" :placeholder="$t('user.InputUsername')" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>-->
      <el-form-item :label="$t('card.State')" prop="status">
        <dict-select v-model="queryParams.status" :dict="dict.type.sys_normal_disable"
          :placeholder="$t('user.UserState')" clearable style="width: 240px" />
      </el-form-item>
      <el-form-item :label="$t('user.CreateTime')">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" :start-placeholder="$t('user.StartTime')" :end-placeholder="$t('user.EndTime')">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          {{ $t("Search") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("Reset") }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:user:add']">{{ $t("Add") }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:user:edit']">{{ $t("Modify") }}
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:user:remove']">{{ $t("Delete") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="$refs.importDialog.show()"
          v-hasPermi="['system:user:import']">{{ $t("user.ImportUser") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:user:export']">{{ $t("Export") }}
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns">
      </right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{
                (queryParams.pageNum - 1) * queryParams.pageSize +
                scope.$index +
                1
              }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('Avatar')" type="index" width="100" align="center">
        <template slot-scope="scope">
          <img class="row-user-avatar" :src="avatar(scope.row)" @click="handleAvatar(scope.row)">
        </template>
      </el-table-column>
      <!--          <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />-->
      <el-table-column :label="$t('user.Username')" align="center" key="userName" prop="userName"
        v-if="columns[1].visible" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('user.Nickname')" align="center" key="nickName" prop="nickName"
        v-if="columns[2].visible" :show-overflow-tooltip="true" />
      <el-table-column :label="$t('user.Department')" align="center" key="deptName" prop="dept.name"
        v-if="columns[3].visible" :show-overflow-tooltip="true" />
      <!--          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible" width="120" />-->
      <el-table-column :label="$t('card.State')" align="center" key="status" v-if="columns[5].visible">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column :label="$t('user.CreateTime')" align="center" prop="createTime" v-if="columns[6].visible"
        width="160">
        <template slot-scope="scope">
          <span>{{ DateFormat(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('Operate')" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.userId !== 1 && scope.row.userId !== loginUser.userId">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:user:edit']">
            {{ $t("Modify") }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']">
            {{ $t("Delete") }}</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['system:user:password', 'system:user:token']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">{{ $t("user.More") }}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handlePassword" icon="el-icon-key" v-hasPermi="['system:user:password']">
                {{ $t("user.ResetPassword") }}
              </el-dropdown-item>
              <!-- <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check" v-hasPermi="['system:user:edit']">
                {{ $t("user.AssignRoles") }}</el-dropdown-item> -->
              <el-dropdown-item command="handleToken" icon="el-icon-key" v-hasPermi="['system:user:token']">
                {{ $t("Token") }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <user-import-dialog ref="importDialog" />
    <avatar-editor-dialog ref="avatarDialog" />
    <user-token-dialog ref="tokenDialog" />
    <user-form-dialog ref="formDialog" @submit="getList" />
  </div>
</template>

<script>
  import systemUserAPI from "@/api/system/user";
  import systemDeptAPI from '@/api/system/dept'
  import DepartmentSelect from "@/views/system/components/DepartmentSelect.vue";
  import AvatarEditorDialog from "@/components/Avatar/AvatarEditorDialog.vue";
  import UserImportDialog from "./list/UserImportDialog.vue";
  import UserFormDialog from "./list/UserFormDialog.vue";
  import UserTokenDialog from "./list/UserTokenDialog.vue";
  import settings from '@/settings'

  export default {
    name: "UserManagePage",
    dicts: ["sys_normal_disable"],
    components: {
      DepartmentSelect,
      AvatarEditorDialog,
      UserImportDialog,
      UserFormDialog,
      UserTokenDialog
    },
    data() {
      return {
        showSearch: true,
        deptName: undefined,
        dateRange: [],
        loading: true,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userName: undefined,
          phonenumber: undefined,
          status: undefined,
          deptId: undefined,
        },
        total: 0,
        userList: null,
        ids: [],
        single: true,
        multiple: true,
        columns: [{
            key: 0,
            label: this.$t("user.UserId"),
            visible: true,
          },
          {
            key: 1,
            label: this.$t("user.Username"),
            visible: true,
          },
          {
            key: 2,
            label: this.$t("user.Nickname"),
            visible: true,
          },
          {
            key: 3,
            label: this.$t("user.Department"),
            visible: true,
          },
          {
            key: 4,
            label: this.$t("user.Phone"),
            visible: true,
          },
          {
            key: 5,
            label: this.$t("State"),
            visible: true,
          },
          {
            key: 6,
            label: this.$t("CreateTime"),
            visible: true,
          },
        ],
      };
    },
    created() {
      this.getList();
      this.getDeptTree();
    },
    computed: {
      loginUser() {
        return this.$store.getters.loginUser
      }
    },
    methods: {
      avatar(item) {
        return item.avatar ? `${settings.baseUrl}${item.avatar}` : require(`@/assets/images/none.png`)
      },
      getList() {
        this.loading = true;
        systemUserAPI.listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
          (response) => {
            this.userList = response.rows
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      getDeptTree() {
        systemDeptAPI.treeselect().then((response) => {
          this.deptOptions = response.data;
        });
      },
      handleStatusChange(row) {
        let text =
          row.status === 0 ?
          this.$t("user.Enable") :
          this.$t("user.Deactivate");
        this.$modal
          .confirm(`${this.$t("user.Sure")}${text}"${row.userName}"${this.$t("user.AreUser")}`)
          .then(function () {
            return changeUserStatus(row.userId, row.status);
          })
          .then(() => {
            this.$modal.msgSuccess(text + this.$t("user.Success"));
          }).catch(() => {
            row.status = row.status === 0 ? 1 : 0
          })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handlePassword":
            this.handlePassword(row);
            break;
          case "handleAuthRole":
            this.handleAuthRole(row);
            break;
          case "handleToken":
            this.handleToken(row)
            break;
          default:
            break;
        }
      },
      handleAvatar(row) {
        this.form = Object.assign({}, row)
        this.$refs['avatarDialog'].show(row.avatar, this.saveAvatar)
      },
      saveAvatar(data) {
        const vm = this
        let formData = new FormData();
        formData.append("file", data);
        formData.append("username", this.form.userName);
        systemUserAPI.uploadAvatar(formData).then((res) => {
          vm.$modal.msgSuccess(this.$t("ModifySuccessful"));
          vm.$refs['avatarDialog'].close();
        });
      },
      handleToken(row) {
        this.$refs['tokenDialog'].show(row)
      },
      /** 新增按钮操作 */
      handleAdd() {
        const user = {
          userId: undefined,
          deptId: undefined,
          userName: undefined,
          nickName: undefined,
          password: undefined,
          phonenumber: undefined,
          email: undefined,
          gender: 1,
          status: 0,
          remark: undefined,
          postIds: [],
          roleIds: [],
        };
        this.$refs['formDialog'].show(user, this.deptOptions)
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        const userId = row.userId || this.ids;
        const vm = this
        systemUserAPI.getUser(userId).then((response) => {
          const user = Object.assign({}, response.data);
          user.password = "";
          vm.$refs['formDialog'].show(user, vm.deptOptions)
        });
      },
      /** 重置密码按钮操作 */
      handlePassword(row) {
        this.$prompt(
            this.$t("Input") + row.userName + this.$t("user.NewPassword"),
            this.$t("Tips"), {
              confirmButtonText: this.$t("OK"),
              cancelButtonText: this.$t("Cancel"),
              closeOnClickModal: false,
              inputPattern: /^.{5,20}$/,
              inputErrorMessage: this.$t("user.PasswordLong"),
            }
          )
          .then(({
            value
          }) => {
            systemUserAPI.resetUserPwd(row.userId, value).then((response) => {
              this.$modal.msgSuccess(
                this.$t("user.ChangePasswordSuccessful") + value
              );
            });
          })
          .catch(() => {});
      },
      /** 分配角色操作 */
      handleAuthRole: function (row) {
        const userId = row.userId;
        this.$router.push("/system/user-auth/role/" + userId);
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.userId || this.ids;
        this.$modal
          .confirm(this.$t("common.SureDelete"))
          .then(function () {
            return systemUserAPI.delUser(userIds);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess(this.$t("DeleteSuccessful"));
          })
          .catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "system/user/export", {
            ...this.queryParams,
          },
          `user_${new Date().getTime()}.xlsx`
        );
      }
    }
  };

</script>
